package org.blog.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.blog.helper.Constants;
import org.blog.helper.HttpUtils;
import org.blog.helper.Result;
import org.blog.model.ModelPassport;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class CheckLoginInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	private ModelPassport getJid(HttpSession session) {
		return (ModelPassport) session.getAttribute(Constants.SESSION_KEY);
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object arg2) throws Exception {
		ModelPassport passport = getJid(request.getSession());
		if (null == passport) {
			if (HttpUtils.isAjax(request)) {
				response.getWriter().print(
						new Result<Object>(401).toJSONString());
			} else {
				StringBuilder url = new StringBuilder();
				url.append("/login");
				response.sendRedirect(url.toString());
			}
			return false;
		}
		return true;
	}

}
